package com.huatai.bi.mapper;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.huatai.bi.entity.TableEntity;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface TableMapper extends BaseMapper<TableEntity> {

	@Update("update tb_table set is_deleted = 1 where datasource_id = #{datasourceId}")
	int deleteByDatasourceId(@Param("datasourceId") Long datasourceId);

	@Update("update tb_table t set column_num = (select count(*) from tb_table_column c where c.is_deleted = 0 and c.table_id=t.id) where is_deleted = 0  and datasource_id= ${datasourceId}")
	int updateColumnNum(@Param("datasourceId") Long datasourceId);

	@Select("SELECT " +
		"a.id, " +
		"a.table_name, " +
		"a.datasource_id, " +
		"LOWER( b.type ) AS dtname, " +
		"  (SELECT d.table_name FROM tb_direct_data_set c LEFT JOIN tb_directory d ON c.id=d.dt_id WHERE a.datasource_id=c.ds_id AND c.table_name=a.table_name AND d.p_id=#{dtId} AND d.is_deleted=0 AND c.type='DB' AND d.is_dir=1) as target_table " +
		"FROM " +
		"tb_table a " +
		"LEFT JOIN tb_datasource b ON a.datasource_id = b.id ${ew.customSqlSegment}")
	List<JSONObject> getTables(@Param("dtId") Long dtId,@Param(Constants.WRAPPER) QueryWrapper wrapper);

	/**
	 * 获取tb_direct_data_set存在条数
	 * @param tableId
	 * @param tableName
	 * @return
	 */
	@Select("SELECT COUNT(1) FROM tb_direct_data_set WHERE ds_id=(SELECT datasource_id FROM tb_table WHERE id=#{tableId}) AND table_name=#{tableName}")
	int getDataSetNum(@Param("tableId") Long tableId,@Param("tableName") String tableName);

	/**
	 * 根据数据源id和表名查询数据
	 * @param tableName
	 * @param datasourceId
	 * @return
	 */
	@Select(" SELECT " +
		" *  " +
		"FROM " +
		" tb_table  " +
		"WHERE " +
		" datasource_id = ${datasourceId}  " +
		" AND ( LOWER ( table_name ) = '${tableName}' OR table_name = '${tableName}' ) ")
	List<TableEntity> getTableListByDsIdAndName(@Param("tableName")String tableName,@Param("datasourceId")Long datasourceId);

//    @Select("SELECT " +
//            "a.id, " +
//            "a.table_name, " +
//            "a.datasource_id, " +
//            "LOWER( b.type ) AS dtname, " +
//            "  (SELECT d.table_name FROM tb_direct_data_set c LEFT JOIN tb_directory d ON c.id=d.dt_id WHERE a.datasource_id=c.ds_id AND c.table_name=a.table_name AND C.type='DB' AND d.is_dir=1) as target_table " +
//            "FROM " +
//            "tb_table a " +
//            "LEFT JOIN tb_datasource b ON a.datasource_id = b.id WHERE a.id IN (#{tableIds})")
//    List<JSONObject> getTables(@Param("tableIds") List<Long> tableIds);
}
